<template>
  <div class="order">
    <div>
      <el-button
        class="btn-add"
        round
        size="small"
        type="primary"
        @click="dialogFormVisible=true"
      >添加分类</el-button>
    </div>
    <el-table :data="list" border v-loading="listLoading" style="width: 100%" height="100%">
      <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
      <el-table-column prop="category_id" label="ID"></el-table-column>
      <el-table-column prop="category_name" label="名称"></el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="添加分类" :visible="dialogFormVisible" @close="dialogFormVisible=false">
      <el-form ref="form" :model="form" label-width="90px">
        <el-form-item label="名称：">
          <el-input v-model="form.category_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible=false">取 消</el-button>
        <el-button type="primary" @click="addClick">添 加</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { classifyList, delClassify, addClassify } from "@/api/category";
export default {
  data() {
    return {
      listLoading: false,
      list: [],
      dialogFormVisible: false,
      form: {
        category_name: ""
      }
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.listLoading = true;
      classifyList().then(res => {
        this.list = res.data;
        this.listLoading = false;
      });
    },
    addClick() {
      if (!this.form.category_name) return this.$message.error("名称不能为空");
      addClassify(this.form).then(res => {
        if (res.code == 200) {
          this.$message.success("添加成功");
          this.form = {};
          this.init();
        } else {
          this.$message.error("添加失败");
        }
        this.dialogFormVisible = false;
      });
    },
    handleDelete(index, data) {
      this.$confirm("此操作将永久删除该分类, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        delClassify({ id: data.category_id }).then(res => {
          if (res.code == 200) {
            this.$message.success("删除成功");
            this.init();
          } else {
            this.$message.error("删除失败");
          }
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.order {
  padding: 20px;
  height: calc(100vh - 120px);
}
.btn-add {
  margin: 0 10px 10px;
}
</style>